package com.lzxuni.modules.organization.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzxuni.common.utils.GetPinyin;
import com.lzxuni.common.utils.StringUtils;
import com.lzxuni.modules.common.entity.PageParameter;
import com.lzxuni.modules.common.entity.Tree;
import com.lzxuni.modules.organization.entity.Authorize;
import com.lzxuni.modules.organization.entity.Role;
import com.lzxuni.modules.organization.entity.User;
import com.lzxuni.modules.organization.entity.UserRelation;
import com.lzxuni.modules.organization.mapper.UserMapper;
import com.lzxuni.modules.organization.mapper.UserRelationMapper;
import com.lzxuni.modules.organization.service.AuthorizeService;
import com.lzxuni.modules.organization.service.UserRelationService;
import com.lzxuni.modules.organization.service.UserService;
import com.lzxuni.modules.shiro.ShiroUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author 孙志强
 * @since 2018-12-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    private UserRelationMapper userRelationMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageInfo<User> queryPage(PageParameter pageParameter, User user) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if (user != null) {
            if (StringUtils.isNotEmpty(user.getCompanyId())) {
                userQueryWrapper.eq("company_id", user.getCompanyId());
            }
            if (StringUtils.isNotEmpty(user.getRealName())) {
                userQueryWrapper.like("real_name", user.getRealName());
            }
        }
        userQueryWrapper.ne("is_system", "Y");
        PageHelper.startPage(pageParameter.getPage(), pageParameter.getRows());
        List<User> userList = this.list(userQueryWrapper);
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        return pageInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insert(User sessionUser, User user) {
        if (ObjectUtils.allNotNull(sessionUser)) {
            user.setCreateUserId(sessionUser.getUserId());
            user.setCreateUsername(sessionUser.getUsername());
        }
        user.setIsSystem("N");
        user.setEnabledMark(1);
        user.setDeleteMark(0);
        user.setQuickQuery(GetPinyin.getPingYin(user.getRealName()));
        user.setSimpleSpelling(GetPinyin.getPinYinHeadChar(user.getRealName()));
        // 初始密码
        String password = "111111";
        // 密码加密
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setSecretkey(salt);
        SimpleHash passwordMd5 = new SimpleHash(ShiroUtils.hashAlgorithmName, password, salt, ShiroUtils.hashIterations);
        user.setPassword(passwordMd5.toString());
        return this.save(user);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(User sessionUser, User user) {
        if (ObjectUtils.allNotNull(sessionUser)) {
            user.setModifyUserId(sessionUser.getUserId());
            user.setModifyUsername(sessionUser.getUsername());
        }
//		//添加的时候，有的信息不应该能改动
//		User oldUser = this.getById(user.getUserId());
//		user.setPassword(oldUser.getPassword());
//		user.setSecretkey(oldUser.getSecretkey());
//		user.setIsSystem(oldUser.getIsSystem());
//		user.setCreateUsername(oldUser.getUsername());
//		user.setCreateUserId(oldUser.getUserId());
//		user.setCreateDate(oldUser.getCreateDate());
        //修改拼音编码
        user.setQuickQuery(GetPinyin.getPingYin(user.getRealName()));
        user.setSimpleSpelling(GetPinyin.getPinYinHeadChar(user.getRealName()));
        return this.updateById(user);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateLastLoginTime(String username) {
        userMapper.updateLastLoginTime(username);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean delete(String userId) {
        //删除关联表条件base_user_relation user_id =userId
        userRelationService.remove(new QueryWrapper<UserRelation>().eq("user_id", userId));
        //删除角色关联关系条件 base_authorize中 object_type=2  object_id = userId
        authorizeService.remove(new QueryWrapper<Authorize>().eq("object_type", "2").eq("object_id", userId));
        return this.removeById(userId);
    }

    @Override
    public boolean validationOldPassword(String userId, String oldPassword) {
        User user = this.getById(userId);
        // 密码加密
        SimpleHash passwordMd5 = new SimpleHash(ShiroUtils.hashAlgorithmName, oldPassword,
                user.getSecretkey(), ShiroUtils.hashIterations);
        if (user.getPassword().equals(passwordMd5.toString())) {
            return true;
        }
        return false;
    }

    //	@Override
//	public boolean updatePassword(String userId, String oldPassword, String newPassword) {
//		User user = new User();
//		user.setPassword(newPassword);
//		user.setUserId(userId);
//		return this.update(user,new QueryWrapper<User>().eq("user_id", userId).eq("password", oldPassword));
//	}
    @Override
    public boolean updatePassword(String userId, String oldPassword, String newPassword) {
        User user = new User();
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setSecretkey(salt);
        SimpleHash passwordMd5 = new SimpleHash(ShiroUtils.hashAlgorithmName, newPassword, salt, ShiroUtils.hashIterations);
        user.setPassword(passwordMd5.toString());
        user.setUserId(userId);
//		return this.update(user,new QueryWrapper<User>().eq("user_id", userId).eq("password", oldPassword));
        return this.updateById(user);
    }

    @Override
    public boolean resetPassword(String userId) {
        User user = this.getById(userId);
        // 密码加密
        SimpleHash passwordMd5 = new SimpleHash(ShiroUtils.hashAlgorithmName, "111111",
                user.getSecretkey(), ShiroUtils.hashIterations);
        return updatePassword(userId, user.getPassword(), passwordMd5.toString());
    }

    @Override
    public User queryByUserName(String username) {
        return this.getOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public Boolean isHzsOrJxs(User user) {
        List<Role> roleList = userRelationMapper.getRoleIdList(user.getUserId());
        boolean flag = false;
        if (roleList != null && roleList.size() > 0) {
            for (Role role : roleList) {
                if (role.getRoleId().equals("287c4f33ce3afafe65066ff97d6ffabe") || role.getRoleId().equals("774612b8f26a6b4fc4653c66a8a53d5d")) {
                    flag = true;
                    break;
                }
            }
        }

        return flag;
    }

    @Override
    public Boolean isYhOrDbgsOrPt(User user) {

        List<Role> roleList = userRelationMapper.getRoleIdList(user.getUserId());
        boolean flag = false;
        if (roleList != null && roleList.size() > 0) {
            for (Role role : roleList) {
                if (role.getRoleId().equals("617a994b821592041a8be46d29a44b4f") || role.getRoleId().equals("f31d4fd7b6edd6de4f149f4d05e4c693") || role.getRoleId().equals("a98632d16e40fb3c29e8c810bcc623ee")) {
                    flag = true;
                    break;
                }
            }
        }

        return flag;
    }

    @Override
    public List<Tree> getTree() {
        List<Tree> list = baseMapper.queryTreeList();
        return list;
    }
}
